<?php
/**********************************************************************************
	
	Displays general info about the currently selected server/database
	
	Copyright (C) 2010 Benjamin Thomas
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 	Author: Benjamin Thomas
	Email: thomas.ben@gmail.com
	Created: 07/15/10
 
	Inputs: 
	Calls: None.
 
 **********************************************************************************
 */

 $lib = dirname(__FILE__) . '/../../';
require_once($lib . 'lib/PageLayout.php');
require_once($lib . 'lib/dateFunctions.php');
require_once($lib . 'lib/MarketDB.php');

$db = new MarketDB();

$sid = $db->getServerId();

$sql = "SELECT count(auctionid) as total, sum(money) as sum, min(time) as first, max(time) as last FROM completedauctions WHERE server = $sid";
$sales = current($db->publicQuery($sql));

$sql = "SELECT count(buyoutid) as total, sum(buy.price) as sum, min(time) as first, max(time) as last FROM completedbuyouts as buy LEFT JOIN chars ON buy.charid = chars.charid WHERE chars.server = $sid";
$buys = current($db->publicQuery($sql));

$sql = "SELECT count(id) as total, sum(buyoutprice) as sum, min(timestamp) as first, max(timestamp) as last FROM scans WHERE realm = $sid";
$scans = current($db->publicQuery($sql));

$sql = "SELECT COUNT( auctionid ) as total , COUNT( DISTINCT buyer ) as agent, MIN( TIME ) as first , MAX( TIME ) as last FROM completedauctions";
$dbsale = current($db->publicQuery($sql));

$sql = "SELECT COUNT( buyoutid ) AS total, COUNT( DISTINCT seller ) AS agent, MIN( TIME ) AS first , MAX( TIME ) AS last FROM completedbuyouts";
$dbbuy = current($db->publicQuery($sql));

$sql = "SELECT COUNT( id ) AS total, COUNT( DISTINCT sellername ) AS agent, MIN( timestamp ) AS first , MAX( timestamp ) AS last FROM scans";
$dbscan = current($db->publicQuery($sql));

$salesDays = ($dbsale['last'] - $dbsale['first']) / 60 / 60 / 24 + 2;
if ($salesDays < 14) { $salesDays = 14; }
$dailysales = createTimestampArray($salesDays,0);
$sql = "SELECT COUNT(auctionid) as total,  FROM_UNIXTIME(time, '%c/%e/%y') as date FROM completedauctions GROUP BY date";
$dbsalesum = $db->publicquery($sql);
foreach($dbsalesum as &$row) {
	$i = array_search(array(strtotime($row['date']) * 1000,0), $dailysales);
	$dailysales[$i][1] = $row['total'];
}

$buyDays = ($dbbuy['last'] - $dbbuy['first']) / 60 / 60 / 24 + 2;
if ($buyDays < 14) { $buyDays = 14; }
$dailybuys =createTimestampArray($buyDays);
$sql = "SELECT COUNT(buyoutid) as total,  FROM_UNIXTIME(time, '%c/%e/%y') as date FROM completedbuyouts GROUP BY date";
$dbbuysum = $db->publicquery($sql);
foreach($dbbuysum as &$row) {
	$i = array_search(array(strtotime($row['date']) * 1000,0), $dailybuys);
	$dailybuys[$i][1] = $row['total'];
}

$scanDays = ($dbscan['last'] - $dbscan['first']) / 60 / 60 / 24 + 2;
if ($scanDays < 14) { $scanDays = 14; }
$dailyscans =createTimestampArray($scanDays);
$sql = "SELECT COUNT(id) as total,  FROM_UNIXTIME(timestamp, '%c/%e/%y') as date FROM scans GROUP BY date";
$dbscansum = $db->publicquery($sql);
foreach($dbscansum as &$row) {
	$i = array_search(array(strtotime($row['date']) * 1000,0), $dailyscans);
	$dailyscans[$i][1] = $row['total'];
}



?>

<table style="width: 95%">
<tr>
<td colspan=16><?php echo $db->getServerName(); ?><br /><hr /></td>
</tr>
<tr>
<td>
	Auctions<br /><hr />
	<div class="server_auctions">
		<table class="tablesorter">
			<thead><tr><th></th><th>Total</th><th>Sum</th><th>Daily Average</th></tr></thead>
			<tbody>
			<?php print serverAuctions($sales, $buys, $scans); ?>
			</tbody>
		</table>
		<hr style="width: 95%"/>
		<div id="pie" style="width:250px; height: 150px;"></div>
	
	</div>
</td><td>
	Top Ten Individual Sales<br /><hr />
	<div class="top10itemsales"><?php toptensales($db); ?> </div>
</td><td>
	Top Ten Individual Purchases<br /><hr />
	<div class="top10purchases"><?php toptenbuys($db); ?></div>
</td></tr>
</table>

<table style="width: 95%">
<tr>
<td colspan=16>Database<BR /><hr />Last updated: <?php echo date("F j, Y g:i:s a (e)", $db->lastUpdate() )?></td>
</tr>
<tr>
<td rowspan=3 width="100%">
	Auctions<br /><hr />
	<div class="db_auctions">
		<table class="tablesorter">
			<thead><tr><th></th><th>Total</th><th>Agents</th><th>Oldest Entry</th><th>Newest Entry</th></tr></thead>
			<tbody>
			<?php print dbAuctions($dbsale, $dbbuy, $dbscan); ?>
			
			</tbody>
		</table>
	</div>
</td>
<td>
	Sales<br /><hr />
	<div id="salesgraph" style="width: 400px; height: 50px;"></div>
</td>
</tr>
<tr>
<td>
	Purchases<br /><hr />
	<div id="buygraph" style="width: 400px; height: 50px;"></div>
</td>
</tr>
<tr>
<td>
	Scans<br /><hr />
	<div id="scangraph" style="width: 400px; height: 50px;"></div>
</td>
</tr>
</table>

<script>
$(function () {
var data = [];
<?php 
	$salepercent = safediv($sales['sum'] , ($sales['sum'] + $buys['sum']));
	$buypercent = safediv($buys['sum'] , ($sales['sum'] + $buys['sum'])) ;
	if (!$salepercent && !$buypercent) {
		echo "data[0] = { label: 'No Data', data: 100 };\n";
	} else {
		echo "data[0] = { label: 'Sales', data: $salepercent };\n";
		echo "data[1] = { label: 'Purchases', data: $buypercent };\n";
	}
?>
	$.plot($("#pie"), data, 
	{
			series: {
				pie: { 
					show: true,
					radius: 1,
					tilt: 0.5,
					label: {
						show: true,
						radius: 1,
						formatter: function(label, series){
							return '<div style="font-size:8pt;text-align:center;padding:2px;color:white;">'+label+'<br/>'+Math.round(series.percent)+'%</div>';
						},
						background: { opacity: 0.8 }
					},
					combine: {
						color: '#999',
						threshold: 0.1
					}
				}
			},
			legend: {
				show: false
			}
	});
});
</script>
<script id="source" language="javascript" type="text/javascript">
$(function () {
	var rd = [];
	rd[0] = <?php echo json_encode($dailybuys); ?>;
	for (var j = 0; j < rd.length; ++j)
		for (var i = 0; i < rd[j].length; ++i)
			rd[j][i][0] += 8* 60 * 60 * 1000;
 
    var options = {
        xaxis: { mode: "time", timeformat: "%m/%d",  },
		yaxis: { min: 0 },
    };
	
	var d = [
		{ data: rd[0], color: "rgb(237,194,64)",lines: { show: true } }	
	]
	
	var plot = $.plot($("#salesgraph"), d, options);
})
</script>
<script id="source" language="javascript" type="text/javascript">
$(function () {
	var rd = [];
	rd[0] = <?php echo json_encode($dailysales); ?>;
	for (var j = 0; j < rd.length; ++j)
		for (var i = 0; i < rd[j].length; ++i)
			rd[j][i][0] += 8* 60 * 60 * 1000;
 
    var options = {
        xaxis: { mode: "time", timeformat: "%m/%d",  },
		yaxis: { min: 0 },
    };
	
	var d = [
		{ data: rd[0], color: "rgb(237,194,64)",lines: { show: true } }	
	]
	
	var plot = $.plot($("#buygraph"), d, options);
})
</script>

<script id="source" language="javascript" type="text/javascript">
$(function () {
	var rd = [];
	rd[0] = <?php echo json_encode($dailyscans); ?>;
	for (var j = 0; j < rd.length; ++j)
		for (var i = 0; i < rd[j].length; ++i)
			rd[j][i][0] += 8* 60 * 60 * 1000;
 
    var options = {
        xaxis: { mode: "time", timeformat: "%m/%d",  },
		yaxis: { min: 0 },
    };
	
	var d = [
		{ data: rd[0], color: "rgb(237,194,64)",lines: { show: true } }	
	]
	
	var plot = $.plot($("#scangraph"), d, options);
})
</script>
	
<?php

function toptensales(&$db) {
	$ind = $db->getIndividualHighestSale(0, 10);
	echo '<table class="tablesorter"><tbody>';
	foreach ($ind as &$row) {
		echo '<tr>';
		echo '<td>' . $row['name'] . '</td>';
		echo '<td>' . getGoldOnly($row['money']) . '</td>';
		echo '<td>' . date('n/d/y', $row['time']). '</td>';
		echo '</tr>';
	}
	echo '</tbody></table>';
}

function toptenbuys(&$db) {
	$sid = $db->getServerID();
	$sql = "SELECT items.itemid as id, items.name as name, buy.price/stackcount as money, time";
	$sql .= " FROM completedbuyouts as buy LEFT JOIN chars as c ON buy.charid = c.charid LEFT JOIN items ON";
	$sql .= " buy.itemID = items.itemID WHERE c.server = $sid ORDER BY money DESC LIMIT 0,10";
	$buys = $db->publicQuery($sql);
	echo '<table class="tablesorter"><tbody>';
	foreach ($buys as &$row) {
		echo '<tr>';
		echo '<td>' . $row['name'] . '</td>';
		echo '<td>' . getGoldOnly($row['money']) . '</td>';
		echo '<td>' . date('n/d/y', $row['time']). '</td>';
		echo '</tr>';
	}
	echo '</tbody></table>';
}	

function serverAuctions($sales, $buys, $scans) {
	$salesDays = ($sales['last'] - $sales['first']) / 60 / 60 / 24 +2;
	$buyDays = ($buys['last'] - $buys['first']) / 60 / 60 / 24+2;	
	$total = $sales['total'] + $buys['total'];
	$scanDays = ($scans['last'] - $scans['first']) / 60 / 60 / 24+2;	
	$sum = $sales['sum'] + $buys['sum'];
	$avg = safediv($sum , max($salesDays, $buyDays));
	
	echo "<tr><td>Auctions</td><td>" . $total . "</td><td>" . getGoldOnly($sum) . "</td><td>" . getGoldOnly($avg) . "</td></tr>";
	echo "<tr><td>Sales</td><td>" . $sales['total'] . "</td><td>" . getGoldOnly($sales['sum']) . "</td><td>" . getGoldOnly(safediv($sales['sum'],$salesDays)) . "</td></tr>";
	echo "<tr><td>Purchases</td><td>" . $buys['total'] . "</td><td>" . getGoldOnly($buys['sum']) . "</td><td>" . getGoldOnly(safediv($buys['sum'],$buyDays)) . "</td></tr>";
	echo "<tr><td>Scans</td><td>" . format($scans['total']) . "</td><td>-</td><td>" . format(safediv($scans['total'] , $scanDays)) . "</td></tr>";


}

function dbAuctions($sale, $buy, $scan) {
	$dstr = "F j, Y g:i:s a";
	echo "<tr><td>Sales</td><td>" . format($sale['total']) . "</td><td>" . format($sale['agent']) . "</td>";
	echo "<td>" . date($dstr, $sale['first']) . '</td><td>' . date($dstr, $sale['last']) . '</td></tr>';
	echo "<tr><td>Purchase</td><td>" . format($buy['total']) . "</td><td>" . format($buy['agent']) . "</td>";
	echo "<td>" . date($dstr, $buy['first']) . '</td><td>' . date($dstr, $buy['last']) . '</td></tr>';
	echo "<tr><td>Scans</td><td>" . format($scan['total']) . "</td><td>" . format($scan['agent']) . "</td>";
	echo "<td>" . date($dstr, $scan['first']) . '</td><td>' . date($dstr, $scan['last']) . '</td></tr>';
}


function format($int) {
	$post = "";
	if ($int > 1000000) {
		$int = $int / 1000;
		$post = "k";
	}
	return number_format($int) . $post;
}

?>